package com.laputacastle.dr.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 文件工具类
 *
 * @author duanlongfei
 * @create 2019/7/20
 */
public final class FileUtils {

    private FileUtils() {
    }

    private static final Logger logger = LoggerFactory
            .getLogger(FileUtils.class);

    // 路径分隔符
    public static final String WIN_PATH_SPLIT = "\\";
    // 路径分隔符
    public static final String UNIX_PATH_SPLIT = "/";
    // txt文件后缀
    public static final String TXT_SUFFIX = ".txt";

    /**
     * 根据操作系统获取路径分隔符
     * @return java.lang.String
     */
    public static String getPathSplit () {
        if (Utils.checkWindows()) {
            return WIN_PATH_SPLIT;
        }
        return UNIX_PATH_SPLIT;
    }

    /**
     * 迭代删除文件夹
     *
     * @param dirPath 文件夹路径
     */
    public static void deleteDir(String dirPath) {
        File file = new File(dirPath);
        if (file.isFile()) {
            file.delete();
        } else {
            File[] files = file.listFiles();
            if (files == null) {
                file.delete();
            } else {
                for (int i = 0; i < files.length; i++) {
                    deleteDir(files[i].getAbsolutePath());
                }
                file.delete();
            }
        }
    }

    /**
     * 一次性读取文本文件内容
     * @param file 文本文件
     * @return java.lang.String
     */
    public static String readToString(File file) {
        String encoding = "UTF-8";
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        String content = null;
        try (FileInputStream in = new FileInputStream(file);){
            in.read(filecontent);
            content = new String(filecontent, encoding);
        } catch (FileNotFoundException e) {
            logger.error(file.getAbsolutePath() + "文件路径有误", e);
        } catch (IOException e) {
            logger.error("文件读取有误", e);
        }
        return content;
    }

    /**
     * 排序压缩包中的文件
     * 文件命名为数字 1..2..3..4....
     * @param zipDocFile
     * @return java.util.List<java.lang.String>
     */
    public static List<String> sortFiles(File zipDocFile) throws Exception {
        String[] list = zipDocFile.list();
        List<String> urlList = new ArrayList<>();
        if (list != null && list.length > 0) {
            for (String name : list) {
                urlList.add(name); //把文件名放入list里面
            }
        }
        Collections.sort(urlList,new Comparator<String>(){
            @Override
            public int compare(String o1, String o2) {
                // 获取 文件名 去掉后面的后缀
                String firstName = o1.split("\\.")[0];
                String secondName = o2.split("\\.")[0];
                // 获取文件名的数值
                int firstNameXh = Integer.parseInt(firstName);
                int secondNameXh = Integer.parseInt(secondName);
                return firstNameXh - secondNameXh;
            }
        });
        return urlList;
    }

    /**
     * 获取文件名(不带后缀)
     * @param filename
     * @return
     */
    public static String getFileName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            int sublit = filename.lastIndexOf('/');
            if ((dot >-1) && (dot < (filename.length() - 1))) {
                filename = filename.substring(0, dot);
            }
            if ((sublit >-1) && (sublit < (filename.length() - 1))) {
                filename = filename.substring(sublit-1);
            }
        }
        return filename;
    }

    /**
     * 获取文件后缀名
     *
     * @param filename
     * @return
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot);
            }
        }
        return filename;
    }

    /**
     * 获取目录下所有文件(按时间排序)
     *
     * @param path
     * @return
     */
    public static List<File> getFileSort(String path) {

        List<File> list = getFiles(path, new ArrayList<File>());

        if (list.size() > 0) {

            Collections.sort(list, new Comparator<File>() {
                @Override
                public int compare(File file, File newFile) {
                    if (file.lastModified() < newFile.lastModified()) {
                        return -1;
                    } else if (file.lastModified() == newFile.lastModified()) {
                        return 0;
                    } else {
                        return 1;
                    }

                }
            });

        }

        return list;
    }

    /**
     *
     * 获取目录下所有文件
     *
     * @param realpath
     * @param files
     * @return
     */
    public static List<File> getFiles(String realpath, List<File> files) {

        File realFile = new File(realpath);
        if (realFile.isDirectory()) {
            File[] subfiles = realFile.listFiles();
            for (File file : subfiles) {
                if (file.isDirectory()) {
                    getFiles(file.getAbsolutePath(), files);
                } else {
                    files.add(file);
                }
            }
        }
        return files;
    }

    /**
     * 读取文件创建时间
     */
    public static String getCreateTime(String filePath){
        String strTime = null;
        try {
            Process p = Runtime.getRuntime().exec("cmd /C dir "
                    + filePath
                    + "/tc" );
            InputStream is = p.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line;
            while((line = br.readLine()) != null){
                if(line.endsWith(".txt")){
                    strTime = line.substring(0,17);
                    break;
                }
            }
        } catch (IOException e) {
            logger.error("文件读取错误", e);
        }
        logger.info("创建时间    " + strTime);
        return strTime;
        //输出：创建时间   2009-08-17  10:21
    }

    /**
     * 创建文件夹
     *
     * @param filePath
     */
    public static void makeDir(String filePath) {
        File path = new File(filePath);
        if (!path.exists()) {
            path.mkdirs();
        }
    }

    /**
     * 下载zip文件
     * @param response
     * @param cPath
     * @throws JAXBException
     */
    public static void download(HttpServletResponse response, String cPath) throws JAXBException {
        try{
            //获取服务器文件
            File file = new File(cPath);
            response.setCharacterEncoding("UTF-8");
            /* 设置文件ContentType类型，这样设置，会自动判断下载文件类型 */
            response.setContentType("application/octet-stream");
            /* 设置文件头：最后一个参数是设置下载文件名 */
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            //输出流
            OutputStream out = response.getOutputStream();
            //输出文件
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            out.close();
            in.close();

        }catch (IOException ioe){
            ioe.printStackTrace();
        }
    }
}
